#include "SceneNode.h"
#include "ISceneManager.h"
//
namespace Euclid
{
	SceneNode::SceneNode(ISceneManager* sceneManager, const std::string& name)
	{
		_sceneManager = sceneManager;
		_name = name;
	}

	SceneNode::~SceneNode()
	{

	}

	void SceneNode::attachObject( RenderableObject* object )
	{
		if (object)
		{
			_attachedObjects[object->getName()] = object;
		}
	}

	RenderableObject* SceneNode::getAttachedObject(const std::string& name)
	{
		AttachedObjectsMap::iterator it = _attachedObjects.find(name);
		if (it != _attachedObjects.end())
		{
			return it->second;
		}
	}

	void SceneNode::detachObject(const std::string& name)
	{
		AttachedObjectsMap::iterator it = _attachedObjects.find(name);
		if (it != _attachedObjects.end())
		{
			_attachedObjects.erase(it);
		}
	}

	void SceneNode::render()
	{
		//
		{
			AttachedObjectsMap::iterator it;
			for (it = _attachedObjects.begin(); it != _attachedObjects.end(); ++it)
			{
				it->second->attachNode(this);
				it->second->preRender();
				it->second->render();
				it->second->postRender();
			}
		}
		
		//
		{		
			NameNodeMap::iterator it;
			for (it = _children.begin(); it != _children.end(); ++it)
			{
				SceneNode* n = static_cast<SceneNode*>(it->second);
				n->render();
			}
		}
	}

	SceneNode* SceneNode::addSceneNodeChild( const std::string& name )
	{
		return static_cast<SceneNode*>(this->addChild(name));
	}

	Node* SceneNode::createChild( const std::string& name )
	{
		if (_sceneManager)
		{
			return _sceneManager->createSceneNode(name);
		}
	}
}
